﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;


using Century.Web.Security.Attributes;
using Century.Web.UI.MVC;


using System;

using System.Web;
using Century.Model.CMS;
using Century.Business.CMS;

namespace Century.Admin.Controllers
{
    //[Authorization(Group = "", Name = "SiteManager")]
    public class PageManagementController : CenturyAdminBaseController
    {

        public PageManagementController(ISiteService siteService) : base(siteService) { }
        //private string defaultImagePath = string.Format("{0}/{1}", ConfManager.Instance.FileExplorer.DefaultPath.ConfigValue, "page_header_default.jpg");
        string defaultImagePath = "page_header_default.jp";
        #region [ Page detail ]

        /// <summary>
        /// Gets Page Detail
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Get(int? id)
        {
            SitePage page = null;
            if (id.HasValue)
            {
                page = siteService.GetPage(id.Value);
                if (page != null)
                {
                    //set current page
                    Session["CurrentPageId"] = page.Id;
                }
                else
                {
                    return new RedirectResult("/Admin");
                }
            }

            return View(page);
        }

        #region Setting Tab

        /// <summary>
        /// Gets Page Settings Tab Content
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Settings(int? id)
        {
            ViewData["Layouts"] = siteService.GetPageLayouts();
            if (id.HasValue)
            {
                SitePage page = siteService.GetPage(id.Value);
                return View(page);
            }
            else
            {
                return View(new SitePage());
            }
        }

        /// <summary>
        /// Saves Page Settings Tab Content
        /// </summary>
        /// <param name="sitePage"></param>
        /// <returns></returns>
        [HttpPost]
        public void Settings(SitePage sitePage)
        {
            SitePage page = siteService.GetPage(sitePage.Id);

            page.Name = sitePage.Name;
            page.LocalName = sitePage.LocalName;
            page.Title = sitePage.Title;
            page.Url = sitePage.Url;
            page.NodeOrder = sitePage.NodeOrder;
            page.MenuDescription = sitePage.MenuDescription;
            page.ImagePath = string.IsNullOrEmpty(sitePage.ImagePath.Trim()) ? defaultImagePath : sitePage.ImagePath;
            page.MenuImagePath = sitePage.MenuImagePath;

            // change home page
            if (!page.IsHomePage && sitePage.IsHomePage)
            {
                // remove homepage flag from old page
                SitePage oldHomePage = siteService.GetSitePages(page.SiteId).FirstOrDefault(c => c.IsHomePage);
                oldHomePage.IsHomePage = false;
                siteService.UpdatePage(oldHomePage);
                // set new page as homepage
                page.IsHomePage = true;
            }

            page.ShowInMenu = sitePage.ShowInMenu;
            page.IsPublished = sitePage.IsPublished;
            page.ShowInRightMenu = sitePage.ShowInRightMenu;
            page.PageLayoutId = sitePage.PageLayoutId;
            siteService.UpdatePage(page);

        }

        #endregion

        #region Properties Tab

        /// <summary>
        /// Gets Page Settings Tab Content
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Properties(int? id)
        {
            if (id.HasValue)
            {
                SitePage page = siteService.GetPage(id.Value);
                return View(page);
            }
            else
            {
                return View(new SitePage());
            }
        }

        /// <summary>
        /// Saves Page Settings Tab Content
        /// </summary>
        /// <param name="sitePage"></param>
        /// <returns></returns>
        [HttpPost]
        public void Properties(SitePage sitePage)
        {
            SitePage page = siteService.GetPage(sitePage.Id);
            page.Description = sitePage.Description;
            page.Keywords = sitePage.Keywords;
            siteService.UpdatePage(sitePage);
        }

        #endregion

        #region Advanced

        public ActionResult Advanced(int? id)
        {
            if (id.HasValue)
            {
                SitePage page = siteService.GetPage(id.Value);
                return View(page);
            }
            else
            {
                return View(new SitePage());
            }
        }

        //public ActionResult AdvancedDetail(SitePageParameterType type)
        //{
        //    return View(type);
        //}

        //[HttpPost]
        //public void AdvancedCSS(FormCollection elements)
        //{
        //    int SitePageId = Convert.ToInt32(elements["SitePageId"]);
        //    string Path = elements["CssPath"];
        //    SitePage page = siteService.GetPage(SitePageId);
        //    if (page != null && Path.Trim().Length > 0)
        //    {
        //        if (page.SitePageParameters != null && !page.SitePageParameters.Any(p => p.ParamValue == Path && p.ParamType == (int)SitePageParameterType.Css))
        //        {
        //            PersistDataUpdater.AddParameterToPage(page, new SitePageParameter
        //            {
        //                ParamName = "CSS",
        //                ParamType = (int)SitePageParameterType.Css,
        //                ParamValue = Path,
        //                SitePageId = page.Id
        //            });
        //        }
        //    }
        //}

        //[HttpPost]
        //public void AdvancedMeta(FormCollection elements)
        //{
        //    int SitePageId = Convert.ToInt32(elements["SitePageId"]);
        //    string MetaName = elements["MetaName"];
        //    string MetaValue = elements["MetaValue"];

        //    SitePage page = PersistData.AvailablePages.First(p => p.Id == SitePageId);
        //    if (page != null && MetaName.Trim().Length > 0 && MetaValue.Trim().Length > 0)
        //    {
        //        if (page.SitePageParameters != null && !page.SitePageParameters.Any(p => p.ParamName == MetaName && p.ParamValue == MetaValue && p.ParamType == (int)SitePageParameterType.CustomMetaTag))
        //        {
        //            PersistDataUpdater.AddParameterToPage(page, new SitePageParameter
        //            {
        //                ParamName = MetaName,
        //                ParamType = (int)SitePageParameterType.CustomMetaTag,
        //                ParamValue = MetaValue,
        //                SitePageId = page.Id
        //            });
        //        }
        //    }
        //}

        //[HttpPost]
        //public void AdvancedJS(FormCollection elements)
        //{
        //    int SitePageId = Convert.ToInt32(elements["SitePageId"]);
        //    string Path = elements["JSPath"];

        //    SitePage page = PersistData.AvailablePages.First(p => p.Id == SitePageId);
        //    if (page != null && Path.Trim().Length > 0)
        //    {
        //        if (page.SitePageParameters != null && !page.SitePageParameters.Any(p => p.ParamValue == Path && p.ParamType == (int)SitePageParameterType.Js))
        //        {
        //            PersistDataUpdater.AddParameterToPage(page, new SitePageParameter
        //            {
        //                ParamName = "JS",
        //                ParamType = (int)SitePageParameterType.Js,
        //                ParamValue = Path,
        //                SitePageId = page.Id
        //            });
        //        }
        //    }
        //}

        //public void AdvancedItemDelete(int? id)
        //{
        //    if (id.HasValue)
        //    {
        //        siteService.RemoveParameterFromPage(id.Value);
        //    }
        //}


        #endregion

        #region Actions Tab

        public ActionResult Actions(int? id)
        {
            return View();
        }

        #endregion

        #endregion

        #region [ Page Detail Button Actions ]

        //[HttpPost]
        //public string GenerateDraftPage(int? id)
        //{
        //    // generate draft page for current page
        //    // redirect to draft edit
        //    if (id.HasValue)
        //    {
        //        SitePage draft = PersistDataUpdater.GetDraftPage(id.Value);
        //        return draft.Name;
        //    }
        //    return string.Empty;
        //}

        //[HttpPost]
        //public string PublishDraftPage(int? id)
        //{
        //    if (id.HasValue)
        //    {
        //        SitePage page = PersistDataUpdater.PublishDraftPage(id.Value);
        //        return page.Id.ToString();
        //    }
        //    return string.Empty;
        //}

        //[HttpPost]
        //public string CancelDraftPage(int? id)
        //{
        //    if (id.HasValue)
        //    {
        //        PersistDataUpdater.CleanDrafts(id.Value);
        //        return PersistData.AvailablePages.Find(p => p.Id == id.Value).LocalName;
        //    }
        //    return string.Empty;
        //}

        #endregion

        #region [ Menu Actions ] : [Add][ChangeStatus][CopyAs]

        public ActionResult Add(int? id)
        {
            ViewData["Layouts"] = siteService.GetPageLayouts();
            if (id.HasValue)
            {
                SitePage parentPage = siteService.GetPage(id.Value);

                SitePage newSitePage = new SitePage();
                newSitePage.ParentId = parentPage.Id;
                newSitePage.SiteId = parentPage.SiteId;
                newSitePage.PageLayoutId = parentPage.PageLayoutId;
                newSitePage.Name = "NewPage";
                newSitePage.ImagePath = defaultImagePath.Replace("~", string.Empty);
                newSitePage.ShowInRightMenu = true;
                return View(newSitePage);
            }
            else
            {
                SitePage newPage = new SitePage();
                newPage.SiteId = Token.CurrentSite.Id;
                newPage.ImagePath = defaultImagePath.Replace("~", string.Empty);
                newPage.MenuImagePath = string.Empty;
                newPage.ShowInRightMenu = true;
                return View(newPage);
            }
        }

        public ActionResult ChangeStatus(int? id)
        {
            if (id.HasValue)
            {
                SitePage page = siteService.GetPage(id.Value);
                if (page != null)
                {
                    // reverse
                    page.IsPublished = !page.IsPublished;
                    // disable all sub pages
                    if (!page.IsPublished)
                    {
                        List<SitePage> subPages = siteService.GetSubPages(page.Id, page.SiteId);
                        foreach (SitePage subP in subPages)
                        {
                            subP.IsPublished = false;
                            siteService.UpdatePage(subP);
                            //PersistData.AvailablePages.Update(p => p.Id == subP.Id, subP);
                        }
                    }
                    siteService.UpdatePage(page);
                    //PersistData.AvailablePages.Update(p => p.Id == id.Value, page);
                }
                return RedirectToAction("Get", new { id = page.Id });
            }
            return RedirectToAction("Get");
        }

        public ActionResult CopyAs(int? id)
        {
            ViewData["Layouts"] = siteService.GetPageLayouts();// PersistData.AllLayouts.ToList();
            if (id.HasValue)
            {
                SitePage parentPage = siteService.GetPage(id.Value);
                parentPage.Id = 0;
                return View(parentPage);
            }
            else
            {
                return View(new SitePage());
            }
        }

        public ActionResult Delete(int? id)
        {
            if (id.HasValue)
            {
                siteService.DeletePage(id.Value);
            }
            return RedirectToAction("Get");
        }

        /// <summary>
        /// Authorized Post-Save Method for page
        /// </summary>
        /// <param name="sitePage"></param>
        [HttpPost]
        public ActionResult SaveNewForm(SitePage sitePage)
        {
            sitePage.Name = sitePage.Name.ToLower();
            sitePage.LocalName = sitePage.LocalName.ToLower();
            siteService.AddNewPage(sitePage);
            //PersistData.AvailablePages.Add(sitePage, true);
            return RedirectToAction("Get", new { sitePage.Id });
        }



        #endregion

        #region [ Remote Checkers ]

        //public JsonResult CheckName(string name, int? id)
        //{
        //    if (!PersistData.AvailablePages.Any(n => n.CountrySiteId == PersistData.CurrentSite.Id && (n.Name.ToLower() == name.ToLower() || n.LocalName.ToLower() == name.ToLower()) && (id.HasValue == false || n.Id != id.Value)))
        //    {
        //        return Json(true, JsonRequestBehavior.AllowGet);
        //    }
        //    else
        //    {
        //        return Json("The name has been taken.", JsonRequestBehavior.AllowGet);
        //    }
        //}

        //public JsonResult CheckLocalName(string localName, int? id)
        //{
        //    if (!PersistData.AvailablePages.Any(n => n.CountrySiteId == PersistData.CurrentSite.Id && (n.LocalName.ToLower() == localName.ToLower() || n.Name.ToLower() == localName.ToLower()) && (id.HasValue == false || n.Id != id.Value)))
        //    {
        //        return Json(true, JsonRequestBehavior.AllowGet);
        //    }
        //    else
        //    {
        //        return Json("The name has been taken.", JsonRequestBehavior.AllowGet);
        //    }
        //}

        #endregion
    }
}